package com.hhhn.wk.main.tab4.mymoney;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alipay.sdk.app.PayTask;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.main.tab4.pwd.SetPayPwdActivity;
import com.hhhn.wk.pay.PayResult;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.StatusBarUtil;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.utils.mi.AES;
import com.hhhn.wk.widget.dialog.DelDialog;
import com.hhhn.wk.widget.dialog.SetPatPwdDialog;
import com.hhhn.wk.widget.dialogpwd.CommonDialog;
import com.hhhn.wk.widget.dialogpwd.CustomerKeyboard;
import com.hhhn.wk.widget.dialogpwd.PasswordEditText;
import com.hhhn.wk.wxapi.Constants_WX;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.Map;
/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/16 0016    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 充值
 *
 * * * * * * * * * * * */
public class RechargeActivity extends BaseActivity implements View.OnClickListener {
    private EditText et_pwd;
    private static final String TAG = "结算支付";
    DecimalFormat df   = new DecimalFormat("######0.00");
    private TextView tv_title;
    private int payTYPEID=2;//0余额 1微信 2支付宝
    private LinearLayout ll_type1;
    private LinearLayout ll_type2;
    private ImageView iv_wx;//微信图标
    private ImageView iv_zfb;//支付宝
//    String orderCode="";//订单编号
    String orderId="";//订单id
    Context context;
    BaseActivity activity;
    private SetPatPwdDialog confirmDialog;
    private LinearLayout ll_pay;
    Intent intent=null;
    /*支付宝 start*/
    final String orderInfo = "订单信息";   // 订单信息
    private static final int SDK_PAY_FLAG = 1;
    public static final int GETRESULT = 2;
    /*支付宝end*/
    /*微信star*/
    private PayReq req=null;
    private IWXAPI msgApi=null;
    /*微信end*/
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    Log.d("支付宝", "payResult: "+payResult);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.d("支付宝", "payResult.getResult(): "+resultInfo);
                    Log.d("支付宝", "payResult.getResultStatus(): "+resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                        mHandler.sendEmptyMessageDelayed(2, 100);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "取消支付", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                //获取支付结果
                case GETRESULT:
                    if (payTYPEID == 1) {//微信
                        getWxResult();//获取微信 支付结果
                    } else {
                        getZFBResult();//获取支付宝 支付结果
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private TextView my_rrb;
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_recharge);
        StatusBarUtil.setTransparentForImageViewInFragment(RechargeActivity.this, null);
        context= RechargeActivity.this;
        activity=this;
//        Intent intent=getIntent();
//        orderCode = intent.getStringExtra("orderCode");
//        orderId = intent.getStringExtra("orderId");
//        deductibleAmount = intent.getStringExtra("deductibleAmount");
//        shiji = intent.getStringExtra("shiji");
//        Log.d("PAY", "订单号: "+orderCode);
        Log.d("PAY", "订单ID: "+orderId);
//        Log.d("PAY", "抵扣: "+deductibleAmount);
//        Log.d("PAY", "实际支付: "+shiji);
    }
    @Override
    protected void initView() {
        et_pwd=findViewById(R.id.et_pwd);
        tv_title=findViewById(R.id.tv_title);
        ll_type1=findViewById(R.id.ll_type1);
        ll_type2=findViewById(R.id.ll_type2);
        iv_wx=findViewById(R.id.iv_wx);
        iv_zfb=findViewById(R.id.iv_zfb);
        ll_pay=findViewById(R.id.ll_pay);
    }
    private void initweixin() {
        req=new PayReq();
        msgApi = WXAPIFactory.createWXAPI(this, null);
    }
    @Override
    protected void initData() {
        //注册广播接收器
        IntentFilter filter = new IntentFilter("com.rrb.pay");
        registerReceiver(broadcastReceiver, filter);
        initweixin();
    }
    @Override
    protected void initClick() {
        ll_type1.setOnClickListener(this);
        ll_type2.setOnClickListener(this);
        ll_pay.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_type1://微信
                payTYPEID=1;
                setTYPEBG();
                break;
            case R.id.ll_type2://支付宝
                payTYPEID=2;
                setTYPEBG();
                break;
            case R.id.ll_pay://支付
                if (et_pwd.getText().toString().trim()==null||"".equals(et_pwd.getText().toString().trim())){
                    toastWk("请输入充值金额");
                    return;
                }
                payPAYD();
//                mBuilder();
//                switch (payTYPEID){
//                    case 0:
//                        Log.e("点击了", "余额支付");
//                        break;
//                    case 1://微信
//                        Log.e("点击了", "微信");
////                        toastWk("微信支付系统维护中");
//                        boolean wxAppInstalledAndSupported = isWXAppInstalledAndSupported();
//                        if (wxAppInstalledAndSupported){
////                            ToastUtils.showShortToast(PayActivity.this,"安装了");
//                            payWXHouTai();
//
//                        }else {
//                            ToastUtils.showShortToast(context,"请检查并安装微信最新版本");
//                        }
//                        break;
//                    case 2://支付宝
//                        Log.e("点击了", "微信");
//                        payZFBHouTai();
//                        break;
//                }
                break;
        }
    }
    private void setTYPEBG(){
        if (payTYPEID==0){
            iv_wx.setImageResource(R.mipmap.pay_n);
            iv_zfb.setImageResource(R.mipmap.pay_n);
            Log.e("选择了", "余额");
        }else
        if (payTYPEID==1){
            iv_wx.setImageResource(R.mipmap.pay_n);
            iv_zfb.setImageResource(R.mipmap.pay_p);
            Log.e("选择了", "微信");
        }else if (payTYPEID==2){
            iv_wx.setImageResource(R.mipmap.pay_p);
            iv_zfb.setImageResource(R.mipmap.pay_n);
            Log.e("选择了", "支付宝");
        }
    }
    /**
     * 一、1.支付宝--调起后台接口
     */
    private void payZFBHouTai() {
        showLoad();
        RequestParams params = AllPublic.getParamsPay(activity,"/rechargePay", true);
//        params.addParameter("cmUserId",activity.getUser().getUid());//用户id
//        params.addParameter("orderId",orderId);//订单id
//        Log.d("PayActivity", params.toString());
        try {
            JSONObject person=new JSONObject();
            person.put("cmUserId",activity.getUser().getUid());//用户id
            person.put("orderId",orderId);//订单id
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);//解密
                JSONObject jsonObject= null;
                try {
                    jsonObject = new JSONObject(result);
                    String data = jsonObject.getString("data");
                    payZFBOfficial(data);
//                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//              payZFBOfficial("alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2018030802336617&biz_content=%7B%22body%22%3A%22%25E8%25B4%25A7%25E7%2589%259B-%25E6%2589%25B9%25E5%258F%2591%22%2C%22out_trade_no%22%3A%2220180323111929266010%22%2C%22passback_params%22%3A%222443976c-7a25-4393-b9df-8417a28a9e48%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%25E8%25B4%25A7%25E7%2589%259B%25E8%25AE%25A2%25E5%258D%2595%25E4%25BA%25A4%25E6%2598%2593%22%2C%22total_amount%22%3A%220.04%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F192.168.0.198%3A8088%2Fhn-mobile-web%2Fmoapi%2Falipay%2FalipayNotify&sign=XrpZHE05FVlrvsKOT9FHT8fdXqtEtgApLRLbH3txB6mwWrNWJoYUJmYUugHIeG4bqiFHOFE0E%2BCWTF6Po0LOeRvIhsPzbdB4sAgkKJUmL6hYlWu6hfLStoJoXoHE%2Bg2VZXpQvt4qajSNRkJwzC6iiJg9hkkFBmZw6gqQJ05y25bvz%2B58vFIlfMlNyi4SC1Ojdeux2LWwv%2FghAaRUrdVpZ6%2Btw2SnwbxhASmGBK50KgllHm1YoB4fGQk4NruFl7vP5suvRYnfSflWWPTjw94MojPA3cOGYqxdyIDNV4wRVu5qi298onfFTKpXd8ipZjIx%2Be3z1%2FAcNpT4bYdRL8oOEQ%3D%3D&sign_type=RSA2&timestamp=2018-03-23+11%3A20%3A14&version=1.0");
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("ImageActivity", "onError");
                ex.printStackTrace();
                Toast.makeText(RechargeActivity.this, "正在生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("ImageActivity", "onCancelled");
                Toast.makeText(RechargeActivity.this, "正在生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("ImageActivity", "onFinished");
                dismissLoad();
            }
        });
    }
    /**
     * 一、2.调起支付宝官方支付
     */
    private void payZFBOfficial(final String order) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(order, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    /**
     * 一、3.调起后台 获取支付宝的结果
     */
    public void getZFBResult() {
        showLoad();
        RequestParams params = AllPublic.getParamsPay(activity, "/rechargeStatus", false);
        params.addParameter("orderId",orderId);//商品订单号
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("获取支付宝的结果", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    if ("0".equals(jsonObject.getString("code"))) {
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
//                        setResult(1,intent);
                        sendBR();
//                        sendBR2();
                        finish();
                    } else {
                        Toast.makeText(context, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("ImageActivity", "onError");
                ex.printStackTrace();
                Toast.makeText(context, "正在生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("ImageActivity", "onCancelled");
                Toast.makeText(context, "正在生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("ImageActivity", "onFinished");
                dismissLoad();
            }
        });
    }
    public void sendBR(){
        LogWk("充值成功发送广播");
        Intent intent = new Intent();
        intent.setAction(Constants.MBroadcastReceiverRecharge);
        sendBroadcast(intent);
    }
//    public void sendBR2(){
//        LogWk("支付成功发送广播");
//        Intent intent = new Intent();
//        intent.setAction(Constants.MBroadcastReceiver000);
//        sendBroadcast(intent);
//    }
    /**
     * 一、1.微信--调起后台接口
     */
    private void payWXHouTai() {
        showLoad();
        initweixin();
        RequestParams params = AllPublic.getParamsPayWX(activity, "/rechargePay", true);
//        params.addParameter("cmUserId",getUser().getUid());//
//        params.addParameter("orderId",orderId);//
        try {
            JSONObject person=new JSONObject();
            person.put("cmUserId",getUser().getUid());//
            person.put("orderId",orderId);//
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String decode) {
                Log.d(TAG, "解析JSON: "+decode);
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject data = new JSONObject(result);
                    if ("0".equals(data.getString("code"))) {//后台指定用微信的code
                        req.appId = Constants_WX.APP_ID;//应用ID
                        JSONObject jsonObject = data.getJSONObject("data");
                        req.nonceStr = jsonObject.getString("nonce_str");//随机字符串
                        req.packageValue = jsonObject.getString("package_value");//扩展字段
                        req.partnerId = jsonObject.getString("mch_id");//商户号
                        req.prepayId = jsonObject.getString("prepay_id");//预支付交易会话ID
                        req.timeStamp = jsonObject.getString("time_stamp");//时间戳
                        req.sign = jsonObject.getString("sign");//签名

                        Log.d(TAG, "微信支付-应用ID: "+Constants_WX.APP_ID);
                        Log.d(TAG, "微信支付-商户号: "+jsonObject.getString("mch_id"));
                        Log.d(TAG, "微信支付-预支付交易会话ID: "+jsonObject.getString("prepay_id"));
                        Log.d(TAG, "微信支付-扩展字段: "+jsonObject.getString("package_value"));
                        Log.d(TAG, "微信支付-随机字符串: "+jsonObject.getString("nonce_str"));
                        Log.d(TAG, "微信支付-时间戳: "+jsonObject.getString("time_stamp"));
                        Log.d(TAG, "微信支付-签名: "+jsonObject.getString("sign"));
                        sendPayReq();
                    } else {
                        Toast.makeText(context, data.getString("return_code"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("ImageActivity", "onError");
                ex.printStackTrace();
                Toast.makeText(context, "生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("ImageActivity", "onCancelled");
                Toast.makeText(context, "生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }

            @Override
            public void onFinished() {
                Log.d("ImageActivity", "onFinished");
                dismissLoad();
            }
        });
    }
    /**
     * 二、2微信回调的支付状态广播的接收器，根据接受的数据判定是否微信回调显示支付成功，显示支付成功后，需要进行获取后台的支付结果
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            int code = intent.getIntExtra("code",-1);
            Log.d(TAG, "微信回调的支付状态: "+code);
            switch (code)
            {
                case 0:
                    mHandler.sendEmptyMessageDelayed(2,100);
                    break;
                case -1:
                    Toast.makeText(context, "支付异常", Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                    Toast.makeText(context, "取消支付", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    Toast.makeText(context, "取消支付", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    /**
     *二、3调取后台数据，获取微信的支付结果
     */
    public void getWxResult(){
        Log.d(TAG, "调取后台数据，获取微信的支付结果");
        showLoad();
        RequestParams params = AllPublic.getParamsPayWX(activity, "/rechargeStatus", true);
        params.addParameter("orderId", orderId);//商品订单号
        Log.d("PayActivity",params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "调取后台数据，获取微信的支付结果"+result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if("0".equals(jsonObject.getString("code"))){
                        if(jsonObject.getString("data").equals("101602"))
                        {
                            Log.d(TAG, "调取后台数据，获取微信的支付结果--成功");
                            Toast.makeText(context,"交易成功",Toast.LENGTH_SHORT).show();
                            sendBR();
//                            sendBR2();
                            finish();
                        }else
                        {
                            Log.d(TAG, "调取后台数据，获取微信的支付结果--失败");
//                            mHandler.sendEmptyMessage(REGETRESULT);
                        }
                        //finish();
                    }else
                    {
                        Log.d(TAG, "调取后台数据，获取微信的支付结果--失败"+jsonObject.getString("resp_code"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("ImageActivity", "onError2");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("ImageActivity", "onCancelled3");
                dismissLoad();
            }
            @Override
            public void onFinished()
            {
                Log.d("ImageActivity", "onFinished4");
                //Toast.makeText(HelpHuanJingBaoHuActivity.this,"支付失败，请重试",Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
        });
    }
    /*检查是否安装微信*/
    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constants_WX.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }
    @Override
    protected void onDestroy() {
        if (broadcastReceiver!=null){
            unregisterReceiver(broadcastReceiver);
        }
        super.onDestroy();
    }
    @Override
    public void onPause() {
        super.onPause();
        if (req!=null){
            req=null;
        }
        if (msgApi!=null){
            msgApi=null;
        }
    }
        /*
         * 调起微信支付
         */
    private void sendPayReq() {
        msgApi.registerApp(Constants_WX.APP_ID);
        msgApi.sendReq(req);
        Log.i(">>>>>", req.partnerId);
    }
    /**
     * 下充值单
     */
    private void payPAYD() {
        showLoad();
//        initweixin();
        RequestParams params = AllPublic.getParamsPayRecharge(activity, "/saveRechargeOrder", true);
        try {
            JSONObject person=new JSONObject();
            person.put("cmUserId",getUser().getUid());//
            person.put("money",et_pwd.getText().toString().trim());//
//            person.put("money",0.01);//
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String decode) {
                Log.d(TAG, "解析JSON: "+decode);
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject data = new JSONObject(result);
                    if ("0".equals(data.getString("code"))) {
                        JSONObject datadata = data.getJSONObject("data");
                        orderId = datadata.has("id") ? datadata.getString("id") : "";
                    switch (payTYPEID){
                    case 1://微信
                        Log.e("点击了", "微信");
                        boolean wxAppInstalledAndSupported = isWXAppInstalledAndSupported();
                        if (wxAppInstalledAndSupported){
                            payWXHouTai();
                        }else {
                            ToastUtils.showShortToast(context,"请检查并安装微信最新版本");
                        }
                        break;
                    case 2://支付宝
                        Log.e("点击了", "支付宝");
                        payZFBHouTai();
                        break;
                }
                    } else {
                        Toast.makeText(context, data.getString("return_code"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("ImageActivity", "onError");
                ex.printStackTrace();
                Toast.makeText(context, "生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("ImageActivity", "onCancelled");
                Toast.makeText(context, "生成支付订单失败，请重试", Toast.LENGTH_SHORT).show();
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("ImageActivity", "onFinished");
                dismissLoad();
            }
        });
    }
}
